package com.lee.wordcounter.impl;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

import com.lee.wordcounter.WordCounter;

public class MapWordCounter implements WordCounter {
    private static final HashMap <String, Integer> map = new HashMap <String, Integer>();
	@Override
	public String[] getTopRankedWords(int rank) {
		// TODO Auto-generated method stub
		ArrayList <String> ret = new ArrayList<String>();
		TreeSet <Integer> values = new TreeSet <Integer>(map.values());
		Iterator <Integer> it = values.descendingIterator();
		Set <String> keys = map.keySet();
		
		while ((it.hasNext()) && (rank > 0)) {
			int v = (Integer)it.next();
			for (String s : keys) {
				if (map.get(s)==v) {
					ret.add(s);
				}
			}
			rank --;
		}
		return ret.toArray(new String [0]);
	}

	@Override
	public void processWords(String fileName) {
		// TODO Auto-generated method stub
		try {
			BufferedReader br= new BufferedReader(new FileReader(fileName));
			String line = br.readLine();
			while (line != null) {
				String [] tokens= line.split(" ");
				for (String s : tokens) {
					addWord(s);
				}
				line = br.readLine();
			}
			br.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}          
	}
	
	public void addWord(String word) {
		if (map.containsKey(word)) {
			int v = map.get(word);
			map.put(word, ++v);
		} else {
			map.put(word, 1);
		}
	}
	
	

}
